package by.dkusch.aircompany.webapp.page.main.panel;

import javax.servlet.http.HttpServletRequest;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.http.handler.RedirectRequestHandler;

import by.dkusch.aircompany.webapp.app.BasicAuthenticationSession;
import by.dkusch.aircompany.webapp.app.WicketWebApplication;
import by.dkusch.aircompany.webapp.page.base.panels.LanguagePanel;
import by.dkusch.aircompany.webapp.page.main.LoginPage;

public class LoginLogoutPanel extends Panel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public LoginLogoutPanel(String id) {
		super(id);
	}

	@Override
	protected void onInitialize() {
		super.onInitialize();

		add(new Link<Void>("login-btn") {
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			protected void onConfigure() {
				super.onConfigure();
				boolean isLoginPage = LoginPage.class.equals(getPage().getClass());
				boolean isLogged = BasicAuthenticationSession.get().isSignedIn();

				setVisible(!(isLogged || isLoginPage));
			}

			@Override
			public void onClick() {
				setResponsePage(new LoginPage());
			}
		});

		add(new Link<Void>("logout-btn") {
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			protected void onConfigure() {
				super.onConfigure();
				setVisible(BasicAuthenticationSession.get().isSignedIn());
			}

			@Override
			public void onClick() {
				final HttpServletRequest servletReq = (HttpServletRequest) getRequest().getContainerRequest();
				servletReq.getSession().invalidate();
				getSession().invalidate();
				getRequestCycle().scheduleRequestHandlerAfterCurrent(new RedirectRequestHandler(WicketWebApplication.LOGIN_URL));

			}
		});

		String userName = BasicAuthenticationSession.get().getUserName();
		add(new Label("userName", new Model<String>(userName)));

		add(new LanguagePanel("languagePanel"));

	}

}
